import { RouteMapManager } from 'my-ts-core/security';
import { AuthenticationService } from 'my-web-core/auth';
import { createRouter, createWebHistory } from 'vue-router';

import authenticationRouter from '@/features/authentication/router';
import homeRouter from '@/features/home/router';
import usersRouter from '@/features/users/router';
import RouteMapConfig from '@/shared/auth/route-map-config';
import { showWarning } from '@/shared/message/message-utils';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...authenticationRouter,
    ...homeRouter,
    ...usersRouter,
    {
      path: '/',
      component: () => import('@/App.vue'),
    },
    {
      path: '',
      redirect: '/home',
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/shared/components/NotFound.vue'),
    },
  ],
});

router.beforeEach((to) => {
  // filter((a): a is string => !!a) acts like filter((a): a is string => a !== null && a !== undefined && a !== '')
  const roleAuthorities = AuthenticationService.currentUser?.fullRoles
    ?.map((r) => r.authority)
    .filter((a): a is string => !!a);

  if (
    AuthenticationService.isAuthenticated &&
    to.path.toLocaleLowerCase().endsWith('login')
  ) {
    // If user has logged in then no need to login page.
    return '/home';
  } else if (
    !RouteMapManager.checkCanActivateRoute(
      RouteMapConfig.getRequestMaps(),
      to.path,
      roleAuthorities,
    )
  ) {
    if (AuthenticationService.isAuthenticated) {
      // Shows message if user already logged in.
      showWarning(
        '对不起，您当前账号没有权限使用该功能，您可以尝试以其它账号重新登录。',
      );
      return false;
    } else {
      // Redirects to login.
      return `/authentication/login?redirectTo=${to.fullPath}`;
    }
  }

  return true;
});

export default router;
